package eiisan.crypto.demo;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

/**
 * @author gragonfly
 * @date 2019/7/17
 **/
public class Base64Demo {
    public static void main(String[] args) {
        // 使用基本编码
        String bStr = "I am a hero!";
        System.out.println("字符串:"+bStr);
        String base64encodedString = Base64.getEncoder().encodeToString(bStr.getBytes(StandardCharsets.UTF_8));
        System.out.println("基本（编码） :" + base64encodedString);

        // 解码
        byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
        System.out.println("基本(解码): " + new String(base64decodedBytes, StandardCharsets.UTF_8));

        //-----------------------
        String urlStr = "TutorialsPoint?java8";
        System.out.println("URL字符串:"+urlStr);
        base64encodedString = Base64.getUrlEncoder().encodeToString(urlStr.getBytes(StandardCharsets.UTF_8));
        System.out.println("URL(编码) :" + base64encodedString);
        base64decodedBytes = Base64.getUrlDecoder().decode(base64encodedString);
        System.out.println("URL(解码): " + new String(base64decodedBytes, StandardCharsets.UTF_8));

        //---------------------------
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 10; ++i) {
            stringBuilder.append(UUID.randomUUID().toString());
        }
        System.out.println("MIME字符串 :"+stringBuilder.toString());
        byte[] mimeBytes = stringBuilder.toString().getBytes(StandardCharsets.UTF_8);
        String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
        System.out.println("MIME(编码) :" + mimeEncodedString);
        base64decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
        System.out.println("MIME(解码): " + new String(base64decodedBytes, StandardCharsets.UTF_8));

    }
}

